<template>
  <div :class="className" :style="{ height: height, width: width }"></div>
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./resize";
import { req } from "../../../../api/base/BaseApi";
// import index from './index'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    toStrain: {
      type: Array,
      default: ["测点1"],
    },
    indexOfValue: String,
  },
  data() {
    return {
      chart: null,
      reqTimer: null,
      setTimer: null,
      xTime: [],
      xTimeQueue: [],
      strainQueues: {},
      strainData: {},
      seriesMaps: [],
      measurePoints: [],
      count: 0,
      listOfMinValue: [10, 0, 140, 119, 106, 6, 5, 0, 1, -1],
      listOfMaxValue: [10, 0, 140, 199, 106, 6, 5, 0, 1, -1],
      listOfAvgValue: [10, 0, 140, 119, 106, 6, 5, 0, 1, -1],
      chartOfName: [
        "主起重量",
        "主起升高度",
        "单位工作循环时间",
        "工作循环总时间",
        "工作循环次数",
        "主起电机1电流A",
        "主起电机1电流B",
        "主起电机1电流C",
        "主起电机2电流A",
        "主起电机2电流B",
      ],
    };
  },
  watch: {
    indexOfValue() {
      console.log("index变化");
      this.setData();
    },
  },
  mounted() {
    this.setData();
  },
  beforeDestroy() {
    this.chart.clear();
    clearInterval(this.reqTimer);
    clearInterval(this.setTimer);
  },
  methods: {
    setData() {
      this.$nextTick(() => {
        // return;
        console.log(this.indexOfMaxValue);
        this.xTime = [];
        this.xTimeQueue = [];
        this.measurePoints = ["测点"];
        clearInterval(this.reqTimer);
        clearInterval(this.setTimer);
        // map 初始化
        this.strainQueues = new Map();
        this.strainData = new Map();
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i];
          this.strainQueues.set(point, []);
          this.strainData.set(point, []);
        }
        this.getPrevChartData();
        // 折线图初始化
        setTimeout(() => {
          this.initChart();
          // 获取更新数据（定时器每 20 秒取一次，每次取 20 个数据）
          this.getChartData();
          this.reqTimer = setInterval(() => {
            this.getChartData();
          }, 20000);
          // 更新数据
          this.setTimer = setInterval(() => {
            this.setChartData();
          }, 1000);
        }, 1000);
      });
    },
    getPrevChartData() {
      for (let i = 0; i < this.measurePoints.length; i++) {
        const point = this.measurePoints[i];
        req("/lifting-service/monitor/prevStrainPage/" + point, "GET", "")
          .then((response) => {
            console.log("dasdsa");
            const tempList = response.data;
            for (let j = 0; j < tempList.length; j++) {
              var temp =
                parseFloat(tempList[j].value) +
                parseFloat(this.listOfAvgValue[this.indexOfValue]);
              //console.log(this.listOfAvgValue[this.indexOfValue])
              console.log(temp);
              const e = {
                name: tempList[j].timestamp,
                value: temp,
              };
              this.strainQueues.get(point).push(e);
              if (i <= 0) {
                this.xTimeQueue.push(tempList[j].time);
              }
            }
            console.log(point);
          })
          .catch((response) => console.log(response));
      }
    },
    getChartData() {
      for (let i = 0; i < this.measurePoints.length; i++) {
        const point = this.measurePoints[i];
        req("/lifting-service/monitor/strainPage/" + point, "GET", "")
          .then((response) => {
            const tempList = response.data;
            for (let j = 0; j < tempList.length; j++) {
              var temp =
                parseFloat(tempList[j].value) +
                parseFloat(this.listOfAvgValue[this.indexOfValue]);
              //console.log(this.listOfAvgValue[this.indexOfValue])
              console.log(temp);
              const e = {
                name: tempList[j].timestamp,
                value: temp,
              };
              this.strainQueues.get(point).push(e);
              if (i <= 0) {
                this.xTimeQueue.push(tempList[j].time);
              }
            }
          })
          .catch((err) => console.log(err));
      }
    },
    setChartData() {
      const time = this.xTimeQueue.shift();
      this.xTime.shift();
      this.xTime.push(time);
      for (let i = 0; i < this.measurePoints.length; i++) {
        const point = this.measurePoints[i];
        const t = this.strainQueues.get(point).shift();
        this.strainData.get(point).shift();
        this.strainData.get(point).push(t);
      }
      this.$emit("func", this.strainData);
      // set series
      this.seriesMaps = [];
      for (let i = 0; i < this.measurePoints.length; i++) {
        const point = this.measurePoints[i];
        const seriesMap = {
          name: point,
          type: "line",
          smooth: true,
          data: this.strainData.get(point),
           itemStyle: {
            normal: {
              color: '#2099D3'
            },
          },
          markPoint: {
            data: [
              {
                name: "最大值",
                type: "max",
              },
              {
                name: "最小值",
                type: "min",
              },
            ],
          },
        };
        this.seriesMaps.push(seriesMap);
      }
      this.chart.setOption({
        xAxis: {
          data: this.xTime,
        },
        series: this.seriesMaps,
      });
    },
    initChart() {
      // const len = this.measurePoints.length
      // for (let i = 0; i < len; i++) {
      //   const temperatureDataI = []
      //   const date = new Date()
      //   for (let j = 0; j < 60; j++) {
      //     const e = {
      //       name: date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(),
      //       value: 300
      //     }
      //     temperatureDataI.push(e)
      //   }
      //   this.temperatureData.set(this.measurePoints[i], temperatureDataI)
      // }
      // for (let j = 0; j < 60; j++) {
      //   this.xTime.push('0')
      // }
      for (let i = 0; i < 60; i++) {
        const time = this.xTimeQueue.shift();
        this.xTime.push(time);
        for (let j = 0; j < this.measurePoints.length; j++) {
          const point = this.measurePoints[j];
          const t = this.strainQueues.get(point).shift();
          this.strainData.get(point).push(t);
        }
      }
      this.$emit("func", this.strainData);
      this.seriesMaps = [];
      for (let i = 0; i < this.measurePoints.length; i++) {
        const point = this.measurePoints[i];
        const seriesMap = {
          name: point,
          type: "line",
          smooth: true,
          data: this.strainData.get(point),
        };
        this.seriesMaps.push(seriesMap);
      }
      if (this.chart != null) {
        this.chart.clear();
      }
      this.chart = echarts.init(this.$el, "macarons");
      this.chart.setOption({
        backgroundColor: "#ffffff",
        title: {
          text: this.chartOfName[this.indexOfValue],
          left: "5%",
          top: "5%",
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            const param0 = params[0];
            const date = new Date(param0.name);
            let s =
              "日期：" +
              date.getFullYear() +
              "/" +
              (date.getMonth() + 1) +
              "/" +
              date.getDate() +
              " " +
              date.getHours() +
              ":" +
              date.getMinutes() +
              ":" +
              date.getSeconds();
            for (let i = 0; i < params.length; i++) {
              s += "<br/>" + params[i].seriesName + ": " + params[i].value;
            }
            return s;
          },
          axisPointer: {
            animation: false,
          },
        },
        legend: {
          right: "5%",
          top: "5%",
          data: this.measurePoints,
          textStyle: {
            color: "#2099d3",
          },
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 20,
          },
        ],
        // 上下左右边距
        grid: {
          left: "8%",
          right: "8%",
          bottom: "10%",
          top: "20%",
        },
        xAxis: {
          type: "category",
          name: "时间",
          boundaryGap: false,
          // splitLine: {
          //   show: false
          // },
          data: this.xTime,
        },
        yAxis: {
          type: "value",
          name: "数据值",
          boundaryGap: false,
          max:
            parseInt(this.listOfAvgValue[this.indexOfValue]) + parseInt("50"),
          min:
            parseInt(this.listOfAvgValue[this.indexOfValue]) - parseInt("50"),
          // splitLine: {
          //   show: false
          // }
        },
        series: this.seriesMaps,
      });
    },
  },
};
</script>

<style scoped>
</style>
